import { useEffect, useState } from 'react';
import { useMediaPredicate } from 'react-media-hook';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from 'src/redux/store';
import { useNavigate } from 'react-router-dom';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Tabs from 'src/component/Tabs';
import { MediaQuery } from 'src/constant/Media';
import { Page } from 'src/constant/Page';
// import { Fill } from 'src/model/Order';
import { openSnackbar } from 'src/redux/uiSlice';
import { calibrateEndDate, calibrateBeginDate, getStartOfYear } from 'src/util/datetimeHelper';
// import { getFills } from 'src/service/orderService';
import { getMyOrder } from 'src/service/orderService';
import { bn, bnFormat } from 'src/util/bigNumber';
import OrderList from './component/OrderList';
import style from './OrderAsk.module.scss';

type Fill = any

const OrderAskPage = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [sentFills, setSentFills] = useState<Fill[]>();
  const [executedFills, setExecutedFills] = useState<Fill[]>();
  const [tabIndex, setTabIndex] = useState<number>(0);
  const [refresh, setRefresh] = useState<boolean>(false);
  const isBiggerThanXsm = useMediaPredicate(MediaQuery.Xsm);
  const token = localStorage.getItem("token")
  const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);
  const begin = calibrateBeginDate(getStartOfYear()).toISOString()
  const end = calibrateEndDate(new Date()).toISOString()
  useEffect(() => {
    // 已付款待确认
    // 待收款
    if (!accountInfo?.FID) return
    getMyOrder({
      FUserID: accountInfo?.FID,
      FState: "全部",
      Sdate: begin,
      Edate: end,
      token: token,
    }).then(res => {
      if (res.success) {
        const sent: Fill[] = [];
        const executed: Fill[] = [];
        res.list.map((item: { FState: string; }) => {
          if (item?.FState === '已付款待确认') sent.push(item);
          if (item?.FState === '待收款') executed.push(item);
        });
        setSentFills(sent);
        setExecutedFills(executed);
      }
    })
    // getFills('sent,executed')
    //   .then((res) => {
    //     const sent: Fill[] = [];
    //     const executed: Fill[] = [];

    //     res.data.map((fill) => {
    //       if (fill.status === 'sent') sent.push(fill);
    //       if (fill.status === 'executed') executed.push(fill);
    //     });
    //     setSentFills(sent);
    //     setExecutedFills(executed);
    //   })
    //   .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  }, [refresh, accountInfo]);

  const onClickAllOrders = () => {
    navigate(Page.OrderAll);
  };

  return (
    <div className={style.self}>
      <BackButton />
      <div className={style.heading}>
        进行中的订单
        <Button appearance="text" onClick={onClickAllOrders}>
          全部订单
        </Button>
      </div>
      {!isBiggerThanXsm && (
        <div className={style.tabs}>
          <Tabs
            labels={["待收款", "已打款"]}
            onChange={(index) => setTabIndex(index)}
            defaultIndex={tabIndex}
          />
        </div>
      )}
      <div className={style.orderDataBlock}>
        {(isBiggerThanXsm || tabIndex === 0) && (
          <div className={style.listBlock}>
            <div className={style.listHeading}>
              {"我的收款银行"}/{"待收款"}{' '}
              <span className={style.amountText}>
                {executedFills && executedFills.length > 0
                  ? `${bnFormat(executedFills.reduce((sum, current) => sum.plus(bn(current.FCNY)), bn(0)))} ${"CNY"}`
                  : '-'}
              </span>
            </div>
            <div className={style.dividerBold} />
            <OrderList dataArray={executedFills} />
          </div>
        )}
        {(isBiggerThanXsm || tabIndex === 1) && (
          <div className={style.listBlock}>
            <div className={style.listHeading}>
              {"买方通知已打款金额"}{' '}
              <span className={style.amountText}>
                {sentFills && sentFills.length > 0
                  ? `${sentFills
                    .reduce((sum, current) => sum.plus(bn(current.FCNY)), bn(0))
                    .toFormat()} ${"CNY"}`
                  : '-'}
              </span>
            </div>
            <div className={style.dividerBold} />
            <OrderList dataArray={sentFills} onRefresh={() => setRefresh(!refresh)} />
          </div>
        )}
      </div>
    </div>
  );
};

export default OrderAskPage;
